<template>
  <div class="execution">
    <basic-container>
      <avue-crud v-model="form" v-bind="bindVal" v-on="onEvent" :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        :before-close="beforeClose">
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="handleBatchDelete">删 除</el-button>
          <el-button type="primary" size="small" @click="handleBatchSubmit">提 交</el-button>
          <el-button type="primary" size="small" @click="handleExport">导 出</el-button>
          <el-button type="primary" size="small" :hidden="true" v-if="false" @click="handlePrint">打 印</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button type="text" size="small"
            v-if="scope.row.handStatus=='2'"
            @click="handleComplain(scope.row)">申 诉</el-button>
          <el-button icon="el-icon-view" type="text" size="small"
            @click="handleView(scope.row,scope.index)">预 览</el-button>
          <el-button type="text" size="small"
            v-if="scope.row.submitStatus=='0'&& scope.row.handStatus=='0'"
            @click="handleEdit(scope.row,scope.index)">编 辑</el-button>
        </template>
        <template slot="swStTicketHandDetailsForm" slot-scope="{disabled}">
          <dynamic-crud :title="dynamicTitle" :data="form.swStTicketHandDetails"
            :option="dynamicOption" :button="!isLineNotice" :disabled="disabled">
          </dynamic-crud>
        </template>
      </avue-crud>
      <open-dialog titile="申 诉" :DialogVisible.sync="dialogVisible">
        <avue-form :option="complainOption" v-model="formComplain">
          <template slot="swStTicketHandDetailsForm">
            <dynamic-crud :title="dynamicTitle" :data="form.swStTicketHandDetails"
              :option="dynamicOption" :button="false">
            </dynamic-crud>
          </template>
        </avue-form>
        <template slot="footer">
          <el-button type="primary" size="small" @click="complainSubmit">保存</el-button>
          <el-button size="small" @click="dialogVisible=false">取 消</el-button>
        </template>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
  import baseCrud from '@/mixins/base-crud';
  import {dateFormat} from '@/util/date';
  import {batchDelete, complain, getDetailObj,submit,exportExcel,putObj} from '@/api/subwaystm/swsttickethand';
  import {tableOptionComplain,startDate, endDate} from "@/const/crud/subwaystm/swsttickethand";
  import {handleExcelResponse} from '@/util/util';

  export default {
    name: 'swsttickethand',
    mixins: [baseCrud('subwaystm/swsttickethand')],
    data() {
      return {
        boxType: '',
        dialogVisible: false,
        formComplain: {},
        tableOptionComplain: tableOptionComplain,
        params: {
          //markId标识：1:车票上交 2:车票回收
          markId: 1
        },
        searchForm: {
          dates1: [startDate, endDate]
        }
      }
    },
    computed: {
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.stm_sw_st_ticket_hand_add, false),
          delBtn: this.vaildData(this.permissions.stm_sw_st_ticket_hand_del, false),
          editBtn: this.vaildData(this.permissions.stm_sw_st_ticket_hand_edit, false)
        };
      },
      isAdd(){
        return this.boxType == 'add'
      },
      isEdit(){
        return this.boxType == 'edit'
      },
      isLineNotice(){
        return this.form.dataSource == '0' // 线网通知
      },
      dynamicTitle(){
        if(this.isLineNotice){
          return '回收明细信息'
        }else{
          return '上交明细信息'
        }
      },
      dynamicOption(){
        let isLine = this.isLineNotice
        return {
          column: [{
            label: '票种',
            prop: 'ticketType',
            type: 'select',
            cell: !isLine,
            cascaderItem: ["ticketName"],
            dicUrl: '/support/swpmticketcardtype/dict',
            props: {
              label: 'mainName',
              value: 'mainEnName'
            },
            disabled: isLine,
            width: 135
          }, {
            label: '车票名称',
            prop: 'ticketName',
            type: 'select',
            cell: this.isAdd || this.isEdit,
            // dicUrl: '/support/swpmticketcardtypeparam/dictAll/{{key}}',
            dicUrl: '/support/swpmticketcardtypeparam/dictSingleAll?mainEnName={{key}}',
            props: {
              label: 'subName',
              value: 'subEnName'
            },
            component: 'ticket-name-select',
            params: {
              ticketAmountKey: 'ticketAmount',
              ticketCountKey: 'ticketCount'
            },
            disabled: this.isAdd,
            width: 160
          },
            {
              "label": "车票种类",
              "prop": "ticketReturnType",
              type: 'select',
              dicUrl: '/admin/dict/type/TICKET_RETURN_TYPE',
              // cell: this.isHandleResultEditable,
              cell: true,
              // disabled: true,
              filterable: true,
              allowCreate: false,
              width: 110,
              rules: [{
                required: true,
                message: "请选择车票种类",
                trigger: "blur"
              }],
            },
            {
            label: '号段',
            prop: 'numberInterval',
            cell: true,
            width: 120
          }, {
            label: '卡号',
            prop: 'cardNumber',
            cell: true,
            width: 120
          }, {
            label: '金额',
            prop: 'ticketAmount',
            type: 'number',
            precision: 2
          }, {
            label: '次数',
            prop: 'ticketCount'
          }, {
            label: '回收数量',
            prop: 'receiveCount',
            hide: !isLine
          }, {
            label: '上交数量',
            prop: 'handCount',
            type: 'number',
            cell: true,
            width: 130
          },{
            label: '实际回收张数',
            prop: 'realReceiveCount',
            type: 'number',
            hide: true
          }, {
            label: '差异张数',
            prop: 'differenceCount',
            type: 'number',
            hide: true
          }, {
            label: '备注',
            prop: 'remark',
            cell: !isLine,
            width: 120
          }]
        }
      },
      complainOption(){
        let option = this.deepClone(this.tableOptionComplain)
        //option.boxType = 'edit'
        option.group[0].display = true
        option.group[3].display = true
        option.group[4].display = true
        return option
      }
    },
    methods: {
      async handleExport(){
        let loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        })
        try {
          let tableSelect = this.$refs.crud.tableSelect;
          let ids = tableSelect.map(row => row.id)
          let param = {
            ids: this.validatenull(ids)?null:ids
          };
          const res = await exportExcel(param);
          handleExcelResponse(res);
        } finally {
          loading.close();
        }
      },
      handleBatchSubmit(){
        var tableSelect = this.$refs.crud.tableSelect
        if(tableSelect.length == 0){
          this.$message.info('请选择要提交的记录')
          return
        }
        for (const table of this.$refs.crud.tableSelect) {
          if (table.submitStatus != "0") {
            this.$message.error("已提交的数据不能重复提交");
            return false;
          }
        }
        var ids = tableSelect.map(row => row.id)
        submit(ids).then(response => {
          this.$message.success('提交成功')
          this.getList(this.page)
        })
      },
      handleBatchDelete(){
        var tableSelect = this.$refs.crud.tableSelect
        if(tableSelect.length == 0){
          this.$message.info('请选择要删除的记录')
          return
        }
        //var ids = tableSelect.map(row => row.id)
        let ids = [];
        for (const table of this.$refs.crud.tableSelect) {
          if (table.submitStatus != "0") {
            this.$message.error("请检查数据，只能删除未提交的");
            return false;
          }
          ids.push(table.id);
        }
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          batchDelete(ids).then(response => {
            this.$message.success('删除成功')
            this.getList(this.page)
          })
        })
      },
      beforeOpen(done, type){
        this.boxType = type
        if(type == 'add'){
          this.tableOption.group[0].display = false
          this.tableOption.group[1].display = true

          setTimeout(()=>{
	      let now = new Date();
	      let hours = now.getHours();
	      if (hours < 6) {
		now.setDate((now.getDate() - 1));
	      }
            //this.form.handTime = dateFormat(new Date())
	    this.form.handTime = dateFormat(now)
            this.form.swStTicketHandDetails = []
            this.form.handPersonName = this.$store.getters.userInfo.nikename;
            this.form.handPersonCode = this.$store.getters.userInfo.userCode;
          }, 0)
          done()
        }else{
          getDetailObj(this.form.id).then(response => {
            this.form.swStTicketHandDetails = response.data.data.swStTicketHandDetails
            if(type != 'view'){
              this.tableOption.group[0].display = false
              this.tableOption.group[1].display = true
              this.form.swStTicketHandDetails.forEach(row => {
                row.$cellEdit = true
              })
            }
            if(this.isLineNotice){
              this.tableOption.group[0].display = true
              this.tableOptionComplain.group[0].display = true
            }else{
              this.tableOption.group[0].display = false
              this.tableOptionComplain.group[0].display = false
            }
            done()
          })
        }
      },
      handleEdit(row, index){
        this.boxType = 'edit'
        this.$refs.crud.rowEdit(row, index)
      },
      rowUpdate(row, index, done, loading){
        for(const item of row.swStTicketHandDetails){
          if(item.ticketName == 'PTDCP'
            && (item.ticketReturnType == null || item.ticketReturnType == undefined || item.ticketReturnType == '')) {
            this.$message.info("普通单程票必须选择车票种类");
            loading();
            return;
          }
          if(this.validatenull(item.ticketType) ||
            this.validatenull(item.ticketName) ||
            this.validatenull(item.handCount) ||
            this.validatenull(item.ticketReturnType)){
            this.$message.info("票种、车票名称、车票种类、上交数量为必填项！");
            loading();
            return;
          }
          // 非单程票 卡号必填
	  /* 20250326去掉必填卡号限制
          if (item.ticketType != 'DCP' && (this.validatenull(item.cardNumber))){
            this.$message.info("非单程票必须填写卡号");
            loading();
            return;
          }
	  */
        }
        putObj(row)
          .then((data) => {
            this.$message.success("修改成功");
            done();
            this.getList(this.page);
          })
          .catch(() => {
            loading();
          });
      },
      handleView(row, index){
        this.tableOption.group[0].display = true
        this.tableOption.group[1].display = true
        this.tableOption.group[3].display = true
        this.tableOption.group[4].display = true
        this.$nextTick(()=>{
          this.dynamicOption.column[9].hide = false;
          this.dynamicOption.column[10].hide = false;
        })
        this.$refs.crud.rowView(row, index)
      },
      beforeClose(done, type){
        if(type == 'view'){
          this.tableOption.group[0].display = false
          this.tableOption.group[1].display = false
          this.tableOption.group[3].display = false
          this.tableOption.group[4].display = false
          this.$nextTick(()=>{
            this.dynamicOption.column[9].hide = true;
            this.dynamicOption.column[10].hide = true;
          })
        }
        done()
      },
      handleComplain(row){
        this.formComplain = row
        this.dialogVisible = true
      },
      complainSubmit(){
        complain(this.formComplain).then(response => {
          this.$message.success('申诉成功')
          this.getList(this.page);
          this.dialogVisible = false
        })
      },
      beforeRowSave(row,done, loading){
        if(row.swStTicketHandDetails.length==0){
          this.$message.info("请添加上交明细信息！");
          loading();
          return;
        }else{
          for(const item of row.swStTicketHandDetails){
            if(item.ticketName == 'PTDCP' && (item.ticketReturnType == null || item.ticketReturnType == undefined || item.ticketReturnType == '')) {
              this.$message.info("普通单程票必须选择车票种类");
              loading();
              return;
            }
            // 非单程票 卡号必填
	    /*
            if (item.ticketType != 'DCP' && (this.validatenull(item.cardNumber))){
              this.$message.info("非单程票必须填写卡号");
              loading();
              return;
            }*/

            if(this.validatenull(item.ticketType) ||
              this.validatenull(item.ticketName) ||
              this.validatenull(item.handCount) ||
              this.validatenull(item.ticketReturnType)){
                this.$message.info("票种、车票名称、车票种类、上交数量为必填项！");
                loading();
                return;
            }
          }
        }
        done();
      },
      beforeRowUpdate(row, index, callback, loading){
        for(const item of row.swStTicketHandDetails){
          if(this.validatenull(item.ticketType) ||
            this.validatenull(item.ticketName) ||
            this.validatenull(item.handCount) ||
            this.validatenull(item.ticketReturnType)){
            this.$message.info("票种、车票名称、车票种类、上交数量为必填项！");
            loading();
            return;
          }else{
            callback();
          }
        }
      }
    }
  }
</script>
